//
//  ContactBankViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/27.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import MessageUI

class ContactBankViewController: KMViewController {
    
    fileprivate let cellId = "contactBankCell"
    fileprivate var dataArray = [String]()
    fileprivate var model = [String:String]() //银行相关信息
    
    fileprivate var bankName = ""
    
    init(bankName:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.bankName = bankName
        self.title = bankName + service_title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        if let model = KMTool.bankContactDetails(bankName: self.bankName) {
            
            if model["phone"] != nil {
                dataArray.append(serviceHotline)
            }
            
            if model["bill"] != nil {
                dataArray.append(queryBills)
            }
            
            if model["lines"] != nil {
                dataArray.append(queryLimit)
            }
            
            if model["points"] != nil {
                dataArray.append(queryPoints)
            }
            
            self.model = model
        }
        
        self.view.backgroundColor = UIColor.mineColor()
        
        if dataArray.count == 0 {
            let label = UILabel()
            label.text = noContactDetails
            label.textColor = UIColor.gray
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
            self.view.addSubview(label)
            
            label.snp.makeConstraints { (make) in
                make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
            }
        }else{
            let tableView = UITableView.init(frame: .zero, style: .plain)
            tableView.backgroundColor = UIColor.clear
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(ContactBankCell.self, forCellReuseIdentifier: cellId)
            tableView.tableFooterView = UIView()
            tableView.bounces = false
            self.view.addSubview(tableView)
            
            tableView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
            }
        }
        
        
    }
    
    //MARK: 查看银行联系详情
    fileprivate func getBankDetails(title:String)->String {
        
        var text = ""
        let phone = self.model["cellPhone"] ?? ""
        
        switch title {
        case serviceHotline://客服热线
            text = call + (self.model["phone"] ?? "")
        case queryBills://账单
            text = send + (self.model["billTip"] ?? "") + to + phone
        case queryLimit://额度
            text = send + (self.model["linesTip"] ?? "") + to + phone
        case queryPoints://积分
            text = send + (self.model["pointsTip"] ?? "") + to + phone
        default:
            break
        }
        
        return text
    }

}

extension ContactBankViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let height = getBankDetails(title: dataArray[indexPath.row]).size(font: RATIO(maxNum: 14), width: ScreenW-RATIO(maxNum: 40)).height-10
        
        return RATIO_H(maxNum: 40) + height
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ContactBankCell
        cell?.accessoryType = .disclosureIndicator
        cell?.titleLabel.text = dataArray[indexPath.row]
        cell?.contextLabel.text = getBankDetails(title: dataArray[indexPath.row])
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let phoneNumber = self.model["cellPhone"] ?? "" //电话号码
        var message = "" //短信内容
        
        switch dataArray[indexPath.row] {
        case serviceHotline://客服热线
            let phone = self.model["phone"] ?? ""
            UIApplication.shared.openURL(NSURL(string: "telprompt://\(phone)")! as URL)
            return
        case queryBills://账单
            message = self.model["bill"] ?? ""
        case queryLimit://额度
            message = self.model["lines"] ?? ""
        case queryPoints://积分
            message = self.model["points"] ?? ""
        default:
            break
        }
        
        let messageVC = MFMessageComposeViewController()
        messageVC.body = message //短信内容
        messageVC.recipients = [phoneNumber] //联系人号码
        messageVC.messageComposeDelegate = self
        self.present(messageVC, animated: true, completion: nil)
    }
}

extension ContactBankViewController : MFMessageComposeViewControllerDelegate {
    
    //MARK: 发送短信
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        
        //关闭短信界面
        controller.dismiss(animated: true, completion: nil)
        
        if result == .cancelled {//取消发送
            KMTool.showText(_text: sendCancel)
        }else if result == .sent {//发送成功
            KMTool.showText(_text: sendSuceess)
        }else {//发送失败
            KMTool.showText(_text: sendFail)
        }
        
        
    }
    
    
    
}
